// https://leetcode.cn/problems/longest-substring-with-at-most-k-distinct-characters/

class Solution {
public:
    int lengthOfLongestSubstringKDistinct(string s, int k) {
        map<char, int> rec;
        int j = 0;
        int sum = 0;
        int maxLen = 0;
        for (int i = 0; i < s.length(); ++i) {
            rec[s[i]]++;
            if (rec[s[i]] == 1) {
                sum++;
                while (sum > k) {
                    rec[s[j]]--;
                    if (rec[s[j]] == 0) sum--;
                    j++;
                }
            } 
            maxLen = max(maxLen, i - j + 1);
        }
        return maxLen;
    }
};